<?php

namespace app\admin\model;

use think\Model;

class Article extends Model
{
    protected static function init()
    {
        // 添加之后
        self::afterInsert(function ($data) {
            if ($data['pic']!='') {
                $arr_tmp=explode(',',$data['pic']);
                $aid=$data->id;
                $arr=array();
                foreach ($arr_tmp as $v) {
                    $arr[]=['aid'=>$aid,'pic'=>$v];
                }
                db('pic')->insertAll($arr);
            }
        });
         // 编辑之后
         self::afterUpdate(function ($data) {
            if ($data['pic']!='') {
                $arr_tmp=explode(',',$data['pic']);
                $aid=$data->id;
                $arr=array();
                foreach ($arr_tmp as $v) {
                    $arr[]=['aid'=>$aid,'pic'=>$v];
                }
                db('pic')->insertAll($arr);
            }
        });
        // 删除之后
        self::afterDelete(function ($data) {
            $res=db('pic')->field('id,pic')->where('aid',$data['id'])->select();
            if ($res) {
                foreach ($res as $k => $v) {
                    $path=ROOT_PATH . "public\\" . $v['pic'];
                    if (file_exists($path)) {
                        @unlink($path);
                    }
                     db('pic')->delete($v['id']);
                }
            }
        });
    }
}
